package uba.ing2.subite.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

public class Account {
	private Collection<AccountEntry> entries;
	private Serializable identifier;

	public static Account createWithInitialBalance(Serializable identifier, Date date, Number value) {
		Account newAccount = new Account(identifier);
		newAccount.register(Credit.ofInitialBalance(date, value));
		return newAccount;
		
	}
	public void register(AccountEntry entry) {
		entries.add(entry);
	}
	public Account(Serializable identifier) {
		this.identifier = identifier;
		entries = new ArrayList<AccountEntry>();
	}

	public Number balanceOn(Date date) {
		return calculateBalanceFor(accountEntriesOn(date));
	}

	private Number calculateBalanceFor(Collection<AccountEntry> entriesOnADate) {
		Number total = 0;
		for (AccountEntry entry : entriesOnADate) {
			total = entry.affectBalance(total);
		}
		return total;
	}
	private Collection<AccountEntry> accountEntriesOn(Date date) {
		Collection<AccountEntry> result = new ArrayList<AccountEntry>();

		for (AccountEntry entry : entries) {
			if (entry.isFor(date)) result.add(entry);
		}

		return result;
	}

	public Serializable identifier() {
		return identifier;
	}
}
